package com.kg.elysia.controller;

import com.kg.elysia.db.Mural;
import com.kg.elysia.service.MuralService;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author zj
 * @since 2025/10/20 14:47
 */
@Slf4j
public class MuralController {

    private final MuralService service;

    public MuralController(MuralService service) {
        this.service = service;
    }

    public void getAll(RoutingContext ctx) {
        log.info("Get all murals");
        service.getAllMurals()
                .onSuccess(result -> ctx.response()
                        .putHeader("Content-Type", "application/json")
                        .end(result.encode()))
                .onFailure(err -> sendError(ctx, 500, err.getMessage()));
    }

    public void create(RoutingContext ctx) {
        JsonObject body = ctx.getBodyAsJson();
        Mural mural = new Mural(body);

        service.addMural(mural)
                .onSuccess(res -> ctx.response()
                        .setStatusCode(201)
                        .end(new JsonObject().put("message", "Created").encode()))
                .onFailure(err -> sendError(ctx, 400, err.getMessage()));
    }

    public void batchSave(RoutingContext ctx) {
        JsonArray body = ctx.getBodyAsJsonArray();

        if (body == null || body.isEmpty()) {
            sendError(ctx, 400, "Empty request body");
            return;
        }

        List<Mural> muralsList = body.stream()
                .filter(JsonObject.class::isInstance)
                .map(obj -> new Mural((JsonObject) obj))
                .toList();

        service.batchAddMurals(muralsList)
                .onSuccess(count -> ctx.response()
                        .setStatusCode(201)
                        .end(new JsonObject()
                                .put("message", "Batch created successfully")
                                .put("count", count)
                                .encode()))
                .onFailure(err -> sendError(ctx, 400, "Batch create failed: " + err.getMessage()));
    }

    private void sendError(RoutingContext ctx, int code, String message) {
        ctx.response()
                .setStatusCode(code)
                .end(new JsonObject().put("error", message).encode());
    }

}
